package xyz.xpman.prisonerfitness.dao;

import android.content.Context;
import android.os.Build;

import androidx.annotation.RequiresApi;
import androidx.arch.core.util.Function;

import org.jetbrains.annotations.NotNull;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import xyz.xpman.prisonerfitness.entity.User;
import xyz.xpman.prisonerfitness.util.FileUtil;
import xyz.xpman.prisonerfitness.util.StrKit;
import xyz.xpman.prisonerfitness.util.XmlUtil;

/**
 * XmlLocalCache
 */
public class XmlLocalCache implements ILocalCache {

    private static final String XML_FILE_NAME = "login_user.xml";
    private static final String ID_COL_NAME = XmlUtil.UNIQUE_FLAG;

    private final Context context;
    private final Function<String, User> func;

    public XmlLocalCache(
            @NotNull Context context, @NotNull Function<String, User> func) {

        this.func = func;
        this.context = context;
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public boolean saveMapToXml(@NotNull Map<String, String> data) {
        String result;

        if (data.isEmpty()) {
            result = "";
        } else {
            result = XmlUtil.toXmlString(data);
        }

        return FileUtil.saveToFile(context, XML_FILE_NAME, result);
    }


    public Map<String, String> getXmlToMap() {
        Map<String, String> data;

        try (FileInputStream fileInputStream = context.openFileInput(XML_FILE_NAME)) {
            data =  XmlUtil.parseToMap(fileInputStream);
        } catch (IOException e) {
            data = Collections.emptyMap();
        }

        return data;
    }




    @Override
    @RequiresApi(api = Build.VERSION_CODES.O)
    public boolean saveLoggedInUserId(int id) {
        Map<String, String> data = new HashMap<>();
        data.put(ID_COL_NAME, String.valueOf(id));

        return saveMapToXml(data);
    }


    @Override
    @RequiresApi(api = Build.VERSION_CODES.O)
    public boolean removeLoggedInUserId() {
        return saveMapToXml(Collections.emptyMap());
    }


    @Override
    public Integer getLoggedInUserId() {
        Integer num = null;
        String id = getXmlToMap().get(ID_COL_NAME);

        if (StrKit.notBlank(id)) {
            num = Integer.parseInt(id);
        }
        return num;
    }


    @Override
    public User getCurrentUser() {
        Integer id = getLoggedInUserId();

        if (null != id) {
            return func.apply(String.valueOf(id));
        }
        return null;
    }


    @Override
    public Integer getCurrentUserId() {
        return getLoggedInUserId();
    }

}
